package com.tiankun.eurekaadmin.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiankun.eurekaadmin.exception.CustomerException;
import com.tiankun.eurekaadmin.pojo.Admin;
import com.tiankun.eurekaadmin.pojo.Jsj;
import com.tiankun.eurekaadmin.service.AdminService;
import com.tiankun.eurekaadmin.util.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author 伍炳清
 * @create 2020-11-11 10:07
 */
@CrossOrigin//跨域
@RestController
@RequestMapping("/admin")
public class AdminController {


    @Resource
    private AdminService adminService;
    @Resource
    RedisTemplate<String, Object> redisTemplate;

    JsonResult jsonResult = new JsonResult();

    //申请验证码
    @PostMapping("/yzm")
    public Map<String, Object> yzm(@RequestBody Map<String, String> map) throws Exception {
        String phone = map.get("phone");

////-----------------------用于测试
//        jsonResult.setCode("1");
//        jsonResult.setMsg("验证码发送成功");
//        // 将数据保存在redis服务器上, 15分钟有效
//        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
//        operations.set("yzm" + phone, "8888", 5, TimeUnit.MINUTES);
//        return jsonResult.getValues();
////---------------------

//        LTAI4G4KHRVAyeQQaFmxA7nc
//        阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                "LTAI4G4KHRVAyeQQaFmxA7nc",
                "11kUEQZEeV4YC7IyiEybRL8rqgs2i1");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "青春商城");
        request.putQueryParameter("TemplateCode", "SMS_204986080");

        //生成4位随机数验证码(1-9)
        String code = "";
        for (int i = 0; i < 4; i++) {
            code += (int) (Math.random() * 9 + 1);
        }
        // 给阿里云短信模板中的${code}赋值，json格式
        request.putQueryParameter("TemplateParam", "{'code':" + code + "}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            // 获取的验证码数据,
            String data = response.getData();
            //{"Message":"OK","RequestId":"CBC83055-A113-483A-91B2-0E4C56CCC643","BizId":"790710603115763709^0","Code":"OK"}

            //利用jsckson的objectMapper冲jspn字符串获取指定字段
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> tmpMap = mapper.readValue(data, Map.class);
            if ("OK".equals(tmpMap.get("Code"))) {
                jsonResult.setCode("1");
                jsonResult.setMsg("验证码发送成功");
                // 将数据保存在redis服务器上, 15分钟有效
                ValueOperations<String, Object> operations = redisTemplate.opsForValue();
                operations.set("yzm" + phone, code, 5, TimeUnit.MINUTES);
                // 设置生存时间
            } else {
                jsonResult.setCode("0");
                jsonResult.setMsg("验证码发送失败,请检查手机号或稍后再试");
            }


        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        jsonResult.setCode("1");
        jsonResult.setMsg("发送成功");
        return jsonResult.getValues();

    }

    @RequestMapping(value = "/regist")
    public Map regist(@RequestBody Map<String, String> map) throws CustomerException {

        //判断验证码
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();

        //利用操作符对象
        Object code = operations.get("yzm" + map.get("phone"));

        if (code == null) {
            jsonResult.setCode("0");
            jsonResult.setMsg("注册失败，验证码失效");
            return jsonResult.getValues();
        }

        if (!map.get("yzm").equals(code)) {
            jsonResult.setCode("0");
            jsonResult.setMsg("注册失败，验证码错误");
            return jsonResult.getValues();
        }

        adminService.addAdmin(map.get("phone"), map.get("password"), map.get("name"));
        jsonResult.setCode("200");
        jsonResult.setMsg("添加成功");

        return jsonResult.getValues();
    }

    @RequestMapping(value = "/login")
    public Map login(@RequestBody Map<String, String> map) throws CustomerException {

        Admin login = adminService.login(map.get("phone"), map.get("password"));
        jsonResult.setCode("200");
        jsonResult.setMsg("登录成功");
        jsonResult.setData(login);
        return jsonResult.getValues();
    }

    @RequestMapping(value = "/updatePassword")
    public Map updatePassword(@RequestBody Map<String, String> map) throws CustomerException {

        //判断验证码
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();

        //利用操作符对象
        Object code = operations.get("yzm" + map.get("phone"));

        if (code == null) {
            jsonResult.setCode("0");
            jsonResult.setMsg("修改失败，验证码失效");
            return jsonResult.getValues();
        }

        if (!map.get("yzm").equals(code)) {
            jsonResult.setCode("0");
            jsonResult.setMsg("修改失败，验证码错误");
            return jsonResult.getValues();
        }

        adminService.updatePassword(map.get("phone"), map.get("newPassword"));
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");

        return jsonResult.getValues();
    }


    @RequestMapping(value = "/getJaShuJu")
    public Map getJaShuJu() throws Exception {

String text= "红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，" +
        "红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，" +
        "红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，" +
        "红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money，红包，钱，money";
        Jsj jsj1 = new Jsj(1, "李四", text, new Date(), 1);
        Jsj jsj2 = new Jsj(2, "张三", text, new Date(), 2);
        Jsj jsj3 = new Jsj(3, "王五", text, new Date(), 1);
        Jsj jsj4 = new Jsj(4, "狗蛋", text, new Date(), 2);
        Jsj jsj5 = new Jsj(5, "张飞", text, new Date(), 1);
        Jsj jsj6 = new Jsj(6, "二狗", text, new Date(), 2);

        List arrayList = new ArrayList();
        arrayList.add(jsj1);
        arrayList.add(jsj2);
        arrayList.add(jsj3);
        arrayList.add(jsj4);
        arrayList.add(jsj5);
        arrayList.add(jsj6);

        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(arrayList);

        return jsonResult.getValues();
    }
}
